import fs from "fs";
import inquirer from "inquirer";
import fse from "fs-extra";
import {getBookList, getBookInfo, getSection, downloadImg, rectifyFileName} from "./handle.js";

const BOOK_PATH = "books"

// 主函数
const main = async () => {
    // 获取所有小册列表
    const books = await getBookList();

    console.log(`小册列表获取成功：共 ${books.length} 本`);

    // 提示用户选择
    const {bookId} = await inquirer.prompt([
        {
            type: "list",
            name: "bookId",
            message: "请选择要下载的小册",
            choices: books,
        },
    ]);

    // 获取小册信息和章节列表
    const {bookInfo, sectionList} = await getBookInfo(bookId);

    // 获取小册名称
    const bookName = rectifyFileName(bookInfo.base_info.title);

    // 创建小册目录、文章中的图片存放目录
    fse.ensureDirSync(BOOK_PATH);
    fse.ensureDirSync(`${BOOK_PATH}/${bookName}`);
    fse.ensureDirSync(`${BOOK_PATH}/${bookName}/images`);

    // 将已完结和未完结的章节分开，只下载已完结的章节
    const finishSectionList = [];
    const unFinishSectionList = [];

    for (const section of sectionList) {
        if (section.status === 1) {
            finishSectionList.push(section);
        } else {
            unFinishSectionList.push(section);
        }
    }

    console.log(`章节获取成功：已完结 ${finishSectionList.length} 章，未完结 ${unFinishSectionList.length} 章`);

    // 遍历所有已完成的章节
    let imageIndex = 0;
    for await (const section of finishSectionList) {
        // 获取章节信息
        const sectionInfo = await getSection(section.id);

        // 章节名称
        const sectionName = rectifyFileName(sectionInfo.title)

        // 章节文件存放路径
        const sectionPath = `${BOOK_PATH}/${bookName}/${section.index}.${sectionName}.md`;

        // 通过正则匹配文章中的图片
        const regex = /!\[(.*?)\]\((.*?)\)/g;
        for (const match of sectionInfo.content.matchAll(regex)) {
            // 从匹配结果中取出图片描述、图片地址
            const [_fullMatch, description, imageUrl] = match;

            // 图片下载地址
            let imageDownloadUrl = imageUrl

            // 图片地址错误则跳过
            if (!imageUrl) {
                continue
            }

            if (!imageUrl.startsWith('http') && imageUrl.startsWith('//')) {
                imageDownloadUrl = 'https:' + imageUrl
            }

            // 给图片名称加个序号防止重复
            imageIndex++;

            // 下载图片
            const relativePath = `images/${(description || 'image')}-${imageIndex}.jpg`;
            try {
                const imgData = await downloadImg(imageDownloadUrl);
                fs.writeFileSync(`${BOOK_PATH}/${bookName}/${relativePath}`, imgData);
            } catch (e) {
                console.error('图片下载失败，已跳过：', imageUrl)
                continue
            }

            // 替换文中的图片地址
            sectionInfo.content = sectionInfo.content.replaceAll(imageUrl, relativePath);
        }

        // 保存文章内容到文件
        fs.writeFileSync(sectionPath, sectionInfo.content);

        console.log(`第 ${section.index} 章下载完成`);
    }

    console.log(`${bookName} 下载完成`);
};

main();
